package com.example.educationblockchain.controller;

import com.alibaba.fastjson.JSON;
import com.example.educationblockchain.model.Message;
import com.example.educationblockchain.service.P2PService;
import com.example.educationblockchain.service.TestService;
import com.example.educationblockchain.util.BlockConstant;
import com.example.educationblockchain.websocket.P2PClient;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class TestController {

    @Autowired
    TestService testService;

    @Autowired
    P2PService p2PService;

    @Autowired
    P2PClient p2PClient;

    @GetMapping("/test")
    @ResponseBody
    public String P2PTest() {
        testService.test();
        System.out.println("P2P测试");
        return "发起测试";
    }

    @GetMapping("/test2")
    @ResponseBody
    public String P2PTest2() {
        p2PService.test2();
        System.out.println("P2P测试");
        return "发起测试";
    }

    @GetMapping("/addPeer")
    public String AddPeerTest(@RequestParam("adr")String address,@RequestParam("pwd")String pwd){

        System.out.println(address);
        System.out.println(pwd);
        p2PClient.connectToPeer(address,pwd);
        return null;
    }

    @GetMapping("/findPeer")
    public String findPeerTest(@RequestParam("adr")String address){

        System.out.println(address);
        List<WebSocket> socketsList = p2PService.getSockets();
        Optional<WebSocket> socket = socketsList.stream()
                .filter(web -> address.equals(web.getRemoteSocketAddress().toString()))
                .findAny();


        if (socket.isPresent()){
            WebSocket ws = socket.get();
            System.out.println(ws.getRemoteSocketAddress().toString());

            Message msg = new Message();
            msg.setType(BlockConstant.P2P_TEST1);
            msg.setData("P2P节点选择测试");
            p2PService.write(ws, JSON.toJSONString(msg));
        }

        return null;
    }

    @GetMapping("/peers")
    public void Peers(){
        List<WebSocket> socketsList = p2PService.getSockets();
        for (WebSocket socket : socketsList){
            System.out.println(socket.toString());
            System.out.println(socket.getRemoteSocketAddress().getAddress().toString());
            System.out.println(socket.getRemoteSocketAddress().getPort());
            System.out.println(socket.getRemoteSocketAddress().toString());
        }
    }

    @GetMapping("/testP2P")
    public void testP2P(){
        testService.testP2P();
    }
}
